<template>
	<div class="user_manage">
		<el-form>
			<el-row>
				<el-col :span="6">
					<el-form-item label="用户名" style="margin-right: 14px">
						<el-input v-model="form.username" placeholder="请输入用户名"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6" style="margin-right: 14px">
					<el-form-item label="邮箱">
						<el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item>
						<el-button  icon="refresh" @click="reset">重置</el-button>
						<el-button type="primary" icon="search" @click="search">搜索</el-button>
						<el-button type="primary" icon="plus" @click="openAddDialog">添加</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<el-table :data="userList" border style="width: 100%;">
			<el-table-column type="index" label="#" align="center"/>
			<el-table-column prop="username" label="用户名" align="center">
				<template #default="scope">
					<el-input
						v-if="scope.row.isEditing"
						v-model="scope.row.editingData.username"
					/>
					<span v-else>{{ scope.row.username }}</span>
				</template>
			</el-table-column>

			<el-table-column prop="email" label="邮箱" align="center">
				<template #default="scope">
					<el-input
						v-if="scope.row.isEditing"
						v-model="scope.row.editingData.email"
						type="email"
					/>
					<span v-else>{{ scope.row.email }}</span>
				</template>
			</el-table-column>

			<el-table-column label="状态" align="center">
				<template #default="scope">
					<el-switch
						:active-value="true"
						v-if="scope.row.isEditing"
						v-model="scope.row.editingData.is_active"
						active-color="#13ce66"
					/>
					<el-tag v-else :type="scope.row.is_active ? 'success' : 'danger'">
						{{ scope.row.is_active ? '启用' : '禁用' }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column label="管理员权限" align="center">
				<template #default="scope">
					<el-switch
						:active-value="true"
						v-if="scope.row.isEditing"
						v-model="scope.row.editingData.is_superuser"
						active-color="#13ce66"
					/>
					<el-icon v-else :color="scope.row.is_superuser ? '#67C23A' : '#F56C6C'">
						<Select v-if="scope.row.is_superuser"/>
						<CloseBold v-else/>
					</el-icon>
				</template>
			</el-table-column>
			<el-table-column label="工作人员权限" align="center">
				<template #default="scope">
					<el-switch
						:active-value="true"
						v-if="scope.row.isEditing"
						v-model="scope.row.editingData.is_staff"
						active-color="#13ce66"
					/>
					<el-icon v-else :color="scope.row.is_staff ? '#67C23A' : '#F56C6C'">
						<Select v-if="scope.row.is_staff"/>
						<CloseBold v-else/>
					</el-icon>
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" width="200">
				<template #default="scope">
					<template v-if="scope.row.isEditing">
						<el-button size="small" type="success" icon="check" @click="saveEdit(scope.row)">保存</el-button>
						<el-button size="small" icon="close" @click="cancelEdit(scope.row)">取消</el-button>
					</template>
					<template v-else>
						<el-button :disabled="scope.row.id == currentUserID" size="small" type="primary" icon="edit" @click="enterEditMode(scope.row)">编辑</el-button>
						<el-button :disabled="scope.row.id == currentUserID" size="small" type="danger" icon="delete" @click="deleteHandel(scope.row)">删除</el-button>
					</template>
				</template>
			</el-table-column>
		</el-table>
		<div style="margin-top: 8px; display: flex; justify-content: flex-end;">
			<el-pagination background layout="prev, pager, next" :total="total" @current-change="pageChange"/>
		</div>


		<!-- 添加用户对话框 -->
		<el-dialog v-model="dialogVisible" title="添加用户" width="30%">
			<el-form :model="newUserForm" :rules="formRules" ref="addFormRef">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="newUserForm.username" placeholder="请输入用户名"/>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="newUserForm.email" placeholder="请输入邮箱"/>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="newUserForm.password" type="password" placeholder="请输入密码"/>
				</el-form-item>
				<el-form-item label="状态">
					<el-switch v-model="newUserForm.is_active" active-text="启用" inactive-text="禁用"/>
				</el-form-item>
				<el-form-item label="权限">
					<el-checkbox
						v-model="newUserForm.is_superuser" label="管理员" />
					<el-checkbox v-model="newUserForm.is_staff" label="工作人员" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitAddUser">确认</el-button>
			</template>
		</el-dialog>
	</div>

</template>
<script setup lang="ts">
import {ref, computed} from 'vue'
import {getUserList, updateUser, adduser, deleteUser} from "/@api/admin";
import {useUserConfig} from '/@/stores/UserInfoConfig'
import {ElMessage, ElMessageBox  } from "element-plus";
const userConfig = useUserConfig()

const currentUserID = computed(()=> {
	return userConfig.userInfo.id
})

// 新增状态
const dialogVisible = ref(false)
const addFormRef = ref()
const newUserForm = reactive({
	username: '',
	email: '',
	password: '',
	is_active: false,
	is_superuser: false,
	is_staff: false

})
// 表单验证规则
const formRules = {
	username: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
	],
	email: [
		{ required: true, message: '请输入邮箱', trigger: 'blur' },
		{ type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 6, message: '密码至少6位', trigger: 'blur' }
	]
}

// 打开添加对话框
const openAddDialog = () => {
	Object.assign(newUserForm, {
		username: '',
		email: '',
		password: '',
		is_active: false,
		is_superuser: false,
		is_staff: false

	})
	dialogVisible.value = true
	nextTick(() => {
		addFormRef.value?.resetFields()
	})
}

// 提交新增用户
const submitAddUser = async () => {
	try {
		await addFormRef.value.validate()
		newUserForm.is_staff = newUserForm.is_staff ? 'True' : 'False'
		newUserForm.is_superuser = newUserForm.is_superuser ? 'True' : 'False'
		newUserForm.is_active = newUserForm.is_active ? 'True' : 'False'
		const res = await adduser(newUserForm)
		ElMessage.success({
			type: res.code == 200 ? 'success' : 'error',
			message: res.msg,
			duration: 2000
		})
		dialogVisible.value = false
		getList() // 刷新列表
	} catch (e) {
		console.error(e)
	}
}

const form = ref({
	username: '',
	page: 1,
	pageSize: 10,
	email: ''
})
const reset = ()=> {
	form.value = {
		username: '',
		page: 1,
		pageSize: 10,
		email: ''
	}
	getList()
}
const search = ()=> {
	form.value.page = 1
	getList()
}

// 进入编辑模式
const enterEditMode = (row: User) => {
	row.isEditing = true
	row.editingData = {
		...row,
		role: row.is_superuser ? 'superuser' : row.is_staff ? 'staff' : 'none'
	}
}

// 保存编辑
const saveEdit = async (row: User) => {
	try {
		const {email,username} = row.editingData
		row.editingData.is_superuser = row.editingData.is_superuser ? 'True' : 'False'
		row.editingData.is_active = row.editingData.is_active ? 'True' : 'False'
		row.editingData.is_staff = row.editingData.is_staff ? 'True' : 'False'
		if(username === ''){
			ElMessage({
				message: '请输入用户名',
				type: 'warning',
				duration: 2000
			})
			return
		}
		if(email === ''){
			ElMessage({
				message: '请输入邮箱',
				type: 'warning',
				duration: 2000
			})
			return
		}
		if(!email.match(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)){
			ElMessage({
				message: '请输入正确的邮箱',
				type: 'warning',
				duration: 2000
			})
			return
		}
		const res = await updateUser(row.editingData)
		ElMessage({
			message: res.msg,
			type: res.code == 200 ? 'success' : 'error',
			duration: 2000
		})
		getList()
	}catch (e){
		console.log(e)
	} finally {
		row.isEditing = false
	}
}

// 取消编辑
const cancelEdit = (row: User) => {
	row.isEditing = false
}
const userList = ref([])
const total = ref(0)
// 获取用户列表时初始化数据
const getList = async () => {
	const res = await getUserList(form.value)
	userList.value = res.data.list.map(user => ({
		...user,
		isEditing: false,
		editingData: null
	}))
	total.value = res.data.total
}
const pageChange = page => {
	form.value.page = page
	getList()
}

const deleteHandel = row => {
	ElMessageBox.confirm(
		'确认删除该用户吗?',
		'Warning',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}
	).then(async() => {
		const res = await deleteUser(row.id)
		ElMessage({
			type: res.code == 200 ? 'success' : 'error',
			message: res.msg,
			duration: 2000
		})
		getList()
	})

}
// 初始化获取数据
getList()
</script>
<style scoped lang="scss">
.user_manage{

}
</style>